import { fileURLToPath, URL } from "node:url";
import { ConfigEnv, defineConfig, PluginOption } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import viteCompression from "vite-plugin-compression";
import legacy from "@vitejs/plugin-legacy";
import Pages from "vite-plugin-pages";
import Layouts from "vite-plugin-vue-layouts";
import pkg from "./package.json" assert { type: "json" };
import { getAllCommitInfo } from "./build/git-utils";

const title = "系统名称";
const description = pkg.description;

async function getEnvVars(configEnv: ConfigEnv) {
  // configEnv
  const env = Object.keys(process.env).filter((key) => key.startsWith("VITE_"));
  const envVars = env.reduce((acc, key) => {
    const value = process.env[key];
    if (value != undefined) {
      acc["import.meta.env." + key] = JSON.stringify(value);
    }
    return acc;
  }, {} as Record<string, string>);

  // 构建时间
  envVars["process.env.VITE_BUILD_TIME"] = JSON.stringify(
    new Date().toISOString()
  );
  envVars["import.meta.env.VITE_VERSION"] = JSON.stringify(pkg.version);
  envVars["import.meta.env.VITE_TITLE"] = JSON.stringify(title);
  envVars["import.meta.env.VITE_DESCRIPTION"] = JSON.stringify(description);
  // 提交ID
  Object.assign(envVars, await getAllCommitInfo());
  return envVars;
}

export default defineConfig(async (configEnv) => {
  const { command } = configEnv;
  const define = await getEnvVars(configEnv);

  const plugins: PluginOption[] = [
    vue(),
    vueJsx(),
    Components({
      resolvers: [
        AntDesignVueResolver({
          importStyle: "less",
        }),
      ],
    }),
    Pages({
      dirs: "src/views",
      exclude: ["**/components/*.vue"],
    }),
    Layouts({
      defaultLayout: "default",
      pagesDirs: "src/views",
      layoutsDirs: "src/layouts",
    }),
  ];
  if (command === "build") {
    plugins.push(
      viteCompression({ algorithm: "gzip", ext: ".gz", threshold: 10240 })
    );
    plugins.push(legacy({ targets: ["defaults", "not IE 11"] }));
  }
  return {
    base: "/",
    plugins: plugins,
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    build: {
      sourcemap: false,
      outDir: "dist",
      rollupOptions: {
        output: {
          chunkFileNames: "js/[name]-[hash].js",
          entryFileNames: "js/[name]-[hash].js",
          // assetFileNames: (assetInfo) => {
          //   const { name, ext } = assetInfo;

          //   if (ext === '.css') {
          //     return `css/${name}${ext}`;
          //   }

          //   // 图片资源
          //   if (/\.(png|jpe?g|svg|gif|webp)$/i.test(ext)) {
          //     return `assets/images/[name]-[hash][ext]`;
          //   }

          //   // 字体资源
          //   if (/\.(woff2?|eot|ttf|otf)$/i.test(ext)) {
          //     return `assets/fonts/[name]-[hash][ext]`;
          //   }

          //   // 其他资源统一放 assets 下
          //   return `assets/[name]-[hash][ext]`;
          // },
        },
      },
    },
    server: {
      port: 8080,
      host: "0.0.0.0",
      proxy: {
        "/api": {
          target: "http://192.168.31.28:8080/plan",
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, ""),
          secure: false,
        },
        "^/regex-api/": {
          target: "http://localhost:4000",
          changeOrigin: true,
        },
      },
    },
    define,
  };
});
